package com.szh.gulimall.ware.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: SongZiHao
 * @date: 2023/2/5
 */
@EnableRabbit
@Configuration
public class RabbitMQConfig {

    /**
     * 使用json序列化机制，对MQ中的消息进行转换
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 普通队列，专门用来接收延时队列中过期的消息，也叫死信队列
     */
    @Bean
    public Queue stockReleaseStockQueue() {
        Queue queue = new Queue("stock.release.stock.queue", true, false,
                false, null);
        return queue;
    }

    /**
     * 延时队列
     */
    @Bean
    public Queue stockDelayQueue() {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("x-dead-letter-exchange", "stock-event-exchange");
        paramMap.put("x-dead-letter-routing-key", "stock.release");
        paramMap.put("x-message-ttl", 120000);
        Queue queue = new Queue("stock.delay.queue", true, false,
                false, paramMap);
        return queue;
    }

    /**
     * 普通交换机、死信交换机，topic类型，绑定多个队列
     */
    @Bean
    public Exchange stockEventExchange() {
        TopicExchange topicExchange = new TopicExchange("stock-event-exchange", true, false);
        return topicExchange;
    }

    /**
     * 交换机与延时队列进行绑定
     */
    @Bean
    public Binding stockLockedBinding() {
        Binding binding = new Binding("stock.delay.queue", Binding.DestinationType.QUEUE,
                "stock-event-exchange", "stock.locked", null);
        return binding;
    }

    /**
     * 交换机与死信队列进行绑定
     */
    @Bean
    public Binding stockReleaseBinding() {
        Binding binding = new Binding("stock.release.stock.queue", Binding.DestinationType.QUEUE,
                "stock-event-exchange", "stock.release.#", null);
        return binding;
    }
}
